package com.rocksdata.mc.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import com.ctz.commonframe.ui.BaseActivity;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.ui.view.NoScrollViewPager;
import com.ctz.commonframe.ui.widget.ViewPagerFragmentAdapter;
import com.ctz.commonframe.utils.ApplicationUtil;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.business.VersionManager;
import com.rocksdata.mc.entity.VersionInfo;
import com.rocksdata.mc.http.HttpClient;
import com.rocksdata.mc.ui.fragment.AnnouncementFragment;
import com.rocksdata.mc.ui.fragment.AnnouncementFragment2;
import com.rocksdata.mc.ui.fragment.HomePageFragment;
import com.rocksdata.mc.ui.fragment.HomePageFragment2;
import com.rocksdata.mc.ui.fragment.MeFragment;
import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    @ViewInject(R.id.tv_main_tab1)
    private TextView tab1;
    @ViewInject(R.id.tv_main_tab2)
    private TextView tab2;
    @ViewInject(R.id.tv_main_tab3)
    private TextView tab3;
    @ViewInject(R.id.tv_main_tab4)
    private TextView tab4;
    @ViewInject(R.id.tv_main_tab5)
    private TextView tab5;
    @ViewInject(R.id.vp_main)
    private NoScrollViewPager vpMain;
    private ProgressDialog pbDownloading;
    private AlertDialog.Builder reloginDialog;

    private List<TextView> tabList = new ArrayList<>();
    private List<Fragment> fragmentList = new ArrayList<>();
    private int currentFragmentIndex;
    private boolean isExceptionDialogShow;
    private AlertDialog.Builder exceptionBuilder;
    private long mExitTime;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        tab1.setTag(0);
        tab2.setTag(1);
        tabList.add(tab1);
        tabList.add(tab2);
        fragmentList.add(new HomePageFragment2());
        fragmentList.add(new AnnouncementFragment());
//        if (UserInfoManager.getCurrentUserType() == UserInfo.USER_TYPE_TEACHER) {
//            tab4.setTag(2);
//            tab5.setTag(3);
//            tabList.add(tab4);
//            tabList.add(tab5);
//            fragmentList.add(new RongyunConversationFragment());
//            fragmentList.add(new MeFragment());
//        } else {
            tab4.setVisibility(View.GONE);
            tab5.setTag(2);
            tabList.add(tab5);
            fragmentList.add(new MeFragment());
//        }

        vpMain.setAdapter(new ViewPagerFragmentAdapter(getSupportFragmentManager(), fragmentList));
        vpMain.setOffscreenPageLimit(tabList.size());
        tab1.setSelected(true);
        vpMain.setCurrentItem(0);

        getVersionInfo();

        HttpClient.setOnAuthErrorListener(new HttpClient.OnAuthErrorListener() {
            @Override
            public void onAuthError(String msg) {
                buildReloginDialog();
//                BusinessManager.getAccountManager().logout();
//                exit();
//                showToast("账户已失效，请重新登录");
//                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(new Intent(MainActivity.this, LoginActivity.class));
            }
        });
    }

    private void buildReloginDialog () {
        if (reloginDialog == null) {
            reloginDialog = new AlertDialog.Builder(MainActivity.this);
            reloginDialog.setTitle("账户已失效，请重新登录");

            reloginDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    exit();
                    BusinessManager.getAccountManager().logout();
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });
            reloginDialog.setCancelable(false);
        }

        reloginDialog.create().show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    private void getVersionInfo() {
        BusinessManager.getVersionManager().getLatestVersionInfo(new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if (isSuccess) {
                    VersionInfo info = (VersionInfo) object;
                    if (VersionManager.isLatestVersion(MainActivity.this, info)) {
                        showVersionDialog(info);
                    }
                }
            }
        });
    }

    private void showVersionDialog(final VersionInfo versionInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("检查版本");
        builder.setMessage("最新版本是" + versionInfo.getVersionName() + ",是否更新");
        builder.setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                update(versionInfo);
            }
        });

        builder.show();
    }

    private void update(final VersionInfo versionInfo){
        if(pbDownloading == null){
            pbDownloading = new ProgressDialog(MainActivity.this);
            pbDownloading.setCanceledOnTouchOutside(false);
            pbDownloading.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pbDownloading.setProgressNumberFormat("%1d MB /%2d MB");
        }
        BusinessManager.getVersionManager().updateVersion(MainActivity.this, versionInfo, new Callback.ProgressCallback<File>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {
                pbDownloading.setTitle("正在下载");
                pbDownloading.setMessage("请稍候...");
                pbDownloading.show();
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                pbDownloading.setMax((int) (total/(1024*1024)));
                pbDownloading.setProgress((int) (current/(1024*1024)));
            }

            @Override
            public void onSuccess(File file) {
                Logger.e("download success, path:" + file.getAbsolutePath());
                pbDownloading.dismiss();
                ApplicationUtil.installApk(MainActivity.this, file.getAbsolutePath());
                exit();
                android.os.Process.killProcess(android.os.Process.myPid());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                pbDownloading.dismiss();
                showToast("下载失败");
                Logger.e("下载失败，url:" + versionInfo.getVersionURL() + ", msg:" + ex.getLocalizedMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                pbDownloading.dismiss();
            }

            @Override
            public void onFinished() {
                pbDownloading.dismiss();
            }
        });
    }

    @Event(value = { R.id.tv_main_tab1, R.id.tv_main_tab2, R.id.tv_main_tab3, R.id.tv_main_tab4, R.id.tv_main_tab5 })
    private void OnClick(View v) {
        if(UserInfoManager.isVisitor() && (v.getId() == R.id.tv_main_tab2 || v.getId() == R.id.tv_main_tab4) ){
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            intent.putExtra("showCancel", true);
            startActivity(intent);
            return;
        }
        for(TextView textView: tabList){
            if (textView == v){
                textView.setSelected(true);
                currentFragmentIndex = (Integer)textView.getTag();
                vpMain.setCurrentItem(currentFragmentIndex);
            }else{
                textView.setSelected(false);
            }
        }
    }

    public void setCurrentFragmentIndex(int index){
        for(TextView textView: tabList){
            if ((Integer)textView.getTag() == index){
                textView.setSelected(true);
                currentFragmentIndex = index;
                vpMain.setCurrentItem(currentFragmentIndex);
            }else{
                textView.setSelected(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null){
            boolean relogin = data.getBooleanExtra(WebViewActivity.EXTRA_KEY_RELOGIN, false);
            if (relogin) {
                BusinessManager.getAccountManager().logout();
                exit();
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                return;
            }
        }
        fragmentList.get(currentFragmentIndex).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 1500) {
                showToast("再按一次退出");
                mExitTime = System.currentTimeMillis();
            } else {
                exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
